package com.zonhar.autofeed.common.device.camera;

import com.hopding.jrpicam.RPiCamera;
import com.hopding.jrpicam.enums.AWB;
import com.hopding.jrpicam.enums.DRC;
import com.hopding.jrpicam.enums.Encoding;
import com.hopding.jrpicam.exceptions.FailedToRunRaspistillException;
import com.zonhar.autofeed.common.util.QiniuUploadUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * 树莓派摄像头驱动类
 * @author Chenhua
 * @date 2023-04-13
 */
public class CameraDevice {

    /**
     * 捕获图像
     * @param filePath
     * @param fileName
     * @return
     */
    public static String takeBufferedStill(String filePath,String fileName) {
        return shootBufferedStill(filePath,fileName);
    }

    /**
     * 初始化相机相机
     * @param filePath
     * @return
     * @throws FailedToRunRaspistillException
     */
    private static RPiCamera initRPiCamera(String filePath) throws FailedToRunRaspistillException {
        RPiCamera piCamera = new RPiCamera(filePath);
        // Change Automatic White Balance setting to automatic
        piCamera.setAWB(AWB.AUTO)
                // Turn off Dynamic Range Compression
                .setDRC(DRC.OFF)
                // Set maximum contrast
                .setContrast(80)
                // Set maximum sharpness
                .setSharpness(80)
                // Set maximum quality
                .setQuality(60)
                // Wait 1 second to take the image
                .setTimeout(1000)
                // Turn on image preview
                .turnOnPreview()
                // Change encoding of images to PNG
                .setEncoding(Encoding.PNG);
        return piCamera;
    }

    /**
     * 捕获图像
     * @param filePath 保存路径
     * @param fileName 文件名
     * @return
     */
    private static String shootBufferedStill(String filePath,String fileName) {
        try {
            RPiCamera piCamera = initRPiCamera(filePath);
            // Take image and store in BufferedImage
            BufferedImage buffImg = piCamera.takeBufferedStill(650, 650);
            QiniuUploadUtil qiniuUploadUtil =new QiniuUploadUtil();
            return qiniuUploadUtil.upload(fileName,bufferedImageToByteArray(buffImg));
        } catch (IOException | InterruptedException | FailedToRunRaspistillException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将BufferedImage转换为byte[]
     * @param image
     * @return
     */
    public static byte[] bufferedImageToByteArray(BufferedImage image) throws IOException{
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        return os.toByteArray();
    }

}
